<template>
<div class="container">
    <div class="leftcol">
        <div class="userimg" @click="sitDown(1)">
            <div :class="cssuserleft" :style="cssLeftPic"></div>
            <div class="usernametext" >{{ leftName }}</div>
        </div>
    </div>
    <div class="chessboard" :style="cssBoard">
        <div :class="chessdata[0].css" id="b0" @click="putchess($event.target)"></div>
        <div :class="chessdata[1].css" id="b1" @click="putchess($event.target)"></div>
        <div :class="chessdata[2].css" id="b2" @click="putchess($event.target)"></div>

        <div :class="chessdata[3].css" id="b3" @click="putchess($event.target)"></div>
        <div :class="chessdata[4].css" id="b4" @click="putchess($event.target)"></div>
        <div :class="chessdata[5].css" id="b5" @click="putchess($event.target)"></div>

        <div :class="chessdata[6].css" id="b6" @click="putchess($event.target)"></div>
        <div :class="chessdata[7].css" id="b7" @click="putchess($event.target)"></div>
        <div :class="chessdata[8].css" id="b8" @click="putchess($event.target)"></div>

    </div>
    <div class="rightcol">
        <div class="userimg" @click="sitDown(2)">
            <div :class="cssuserright" :style="cssRightPic"></div>
            <div class="usernametext">{{ rightName }}</div>
        </div>
    </div>
    <div class="buttonList">
        <button class="giveup" @click="giveUpContest" :style="cssGetUpGiveUp">放弃对局</button>
        <button class="goaway" @click="getUp" :style="cssGetUpButton">离开对局</button>
    </div>
</div>
</template>

<script setup name="chessboard">
    import axios from 'axios'
    import { ref, reactive, computed, onMounted, onUnmounted, watch} from "vue"
    import {useRouter} from "vue-router"
    import settings from '@/config/config'
    let userId = ref()
    let picId = ref()
    let chessKey = ''
    let watchList = Array()
    const router = useRouter()

    let leftName = ref('空'), rightName = ref('空')

    let chessStatus = ref(0)
    let gameStatus = ref(false)
    let winner = ref(0)


    // #region cssref
    let cssGetUpButton = ref({'display': 'none'})
    let cssGetUpGiveUp = computed(() => {
        if (gameStatus.value == true) {
            return {
                'display': 'inline-block'
            }
        }
        else {
            return {
                'display': 'none'
            }
        }
    })

    // #endregion

    // 对局数据
    let seatsA = ref(-1), seatsB = ref(-1), conChessStaus = ref(), step = ref(), boardData

    onMounted(()=>{
        let tempUserId = localStorage.getItem('userId')
        let tempPicId = localStorage.getItem('picId')
        if (!tempUserId || !tempPicId) {
            router.push('/')
        }
        else {
            userId.value = tempUserId
            picId.value = tempPicId
        }
        tongbuContest()
    })
    
    // 构建事件流
    let updateLst = new EventSource(settings.backURL + '/api/stream')
    updateLst.onmessage = async function(event) {
        if (event.data == 'alert') {
            alert('警报')
        }
        else if (event.data == 'sycdata') {
            await tongbuContest()
        }
    }


    // #region 棋盘
    let cssBoard = ref({'cursor': 'not-allowed'})
    let cssuserleft = computed(()=> {
        if (gameStatus.value == false) {
            return "headpic"
        }
        else {
            if (winner.value == 1) {
                return 'headpic win'
            }
            if (conChessStaus.value == 1) {
                return 'headpic userSelected'
            }
            else {
                return 'headpic'
            }
        }
    })
    let cssuserright = computed(()=>{
        if (gameStatus.value == false) {
            return "headpic"
        }
        else {
            if (winner.value == 2) {
            return 'headpic win'
            }
            if (conChessStaus.value == 2) {
                return 'headpic userSelected'
            }
            else {
                return 'headpic'
            }
        }
    })

    let chessdata = reactive({
        0: { status: 0, css: 'block', timer: 0},
        1: { status: 0, css: 'block', timer: 0},
        2: { status: 0, css: 'block', timer: 0},

        3: { status: 0, css: 'block', timer: 0},
        4: { status: 0, css: 'block', timer: 0},
        5: { status: 0, css: 'block', timer: 0},

        6: { status: 0, css: 'block', timer: 0},
        7: { status: 0, css: 'block', timer: 0},
        8: { status: 0, css: 'block', timer: 0},

    })


    async function putchess(event) {
        if (gameStatus.value == false) {
            return
        }
        if (conChessStaus.value != chessStatus.value) {
            return
        }
        console.log(step.value, chessStatus.value, conChessStaus.value)
        let id = parseInt(event.id[1])
        if (chessdata[id].status != 0 || gameStatus.value == false) return
        chessdata[id].status = chessStatus.value
        if (chessdata[id].status != 0) {
            chessdata[id].timer = 6
        }
        // 发送数据
        await axios.post(settings.backURL + '/api/putChess', {
            step: step.value,
            chessStatus: chessStatus.value,
            boardBlock: id,
            chessKey: chessKey,
            chessdata: JSON.stringify(chessdata)
        })
    }


    function gameInit() {
        winner.value = 0 
        chessdata = {
            0: { status: 0, css: 'block', timer: 0},
            1: { status: 0, css: 'block', timer: 0},
            2: { status: 0, css: 'block', timer: 0},

            3: { status: 0, css: 'block', timer: 0},
            4: { status: 0, css: 'block', timer: 0},
            5: { status: 0, css: 'block', timer: 0},

            6: { status: 0, css: 'block', timer: 0},
            7: { status: 0, css: 'block', timer: 0},
            8: { status: 0, css: 'block', timer: 0},    
        }
    }

    // #endregion

    // #region 对局

    function giveUpContest() {
        axios.post(settings.backURL + '/api/initContest')
        .catch((e) => {
            alert("重启对局异常")
        })
    }

    // 离开座位 
    function getUp() {
        axios.post(settings.backURL + '/api/getUp', {
            id: userId.value
        })
    }

    // #endregion

    // #region 上座
    let cssLeftPic = ref({})
    let cssRightPic = ref({})
    let controlStatus = ref(false)
    
    watchList.push(
        watch(seatsA, (newValue, oldValue) => {
        if (newValue == -1) {
            cssLeftPic.value = {}
            leftName.value = '空'
            return
        }
        axios.post(settings.backURL + '/api/getUserInfo', {
            'id': seatsA.value
        }).then((res) => {
            let tempdata = res.data
            let picId = tempdata.picId
            leftName.value = tempdata.name
            const url = `${settings.backURL}/images?picId=${picId}`
            cssLeftPic.value = {
                'background-image': `url(${url})`
            }
        })
    }))
    watchList.push(
        watch(seatsB, (newValue, oldValue) => {
        if (newValue == -1) {
            cssRightPic.value = {}
            rightName.value = '空'
            return
        }
        axios.post(settings.backURL + '/api/getUserInfo', {
            'id': seatsB.value
        }).then((res) => {
            let tempdata = res.data
            let picId = tempdata.picId
            rightName.value = tempdata.name
            const url = `${settings.backURL}/images?picId=${picId}`
            cssRightPic.value = {
                'background-image': `url(${url})`
            }
        })
    }))
    watchList.push(watch(controlStatus, (newValue) => {
        gameStatus.value = newValue
        cssBoard.value = gameStatus.value ? {'cursor': 'pointer'} : {'cursor': 'not-allowed'}
    }))


    async function sitDown(pos) {
        if (pos == 1) {
            chessStatus.value = 1
            await axios.post(settings.backURL + '/api/sitdown', {
                pos: 1,
                id: userId.value
            }).then((response) => {
                if (response.data.status == 0) {
                    chessKey = response.data.chessKey
                }
                else {
                    alert(response.data.msg)
                }
            })
        }
        else if(pos == 2) {
            chessStatus.value = 2
            await axios.post(settings.backURL + '/api/sitdown', {
                pos: 2,
                id: userId.value
            }).then((response) => {
                if (response.data.status == 0) {
                    chessKey = response.data.chessKey
                }
                else {
                    alert(response.data.msg)
                }
            })
        }
    }

    async function tongbuContest() {
        axios.post(settings.backURL + '/api/getContest', {})
        .then((response) => {
            let data = response.data
            seatsA.value = data.seatsA
            seatsB.value = data.seatsB
            conChessStaus.value = data.chessRight
            step.value = data.step
            chessdata = JSON.parse(data.chessdata)
            controlStatus.value = data.gameStatus
            winner.value = data.winner


            if (controlStatus.value == false) {
                gameInit()
            }

            if (seatsA.value == userId.value || seatsB.value == userId.value) {
                if (seatsA.value == userId.value) {
                    chessStatus.value = 1
                }
                else if (seatsB.value == userId.value) {
                    chessStatus.value = 2
                }
                else {
                    chessStatus.value = 0
                }
                cssGetUpButton.value = {
                    'display': 'inline-block',
                }
            }
            else {
                cssGetUpButton.value = {
                    'display': 'none'
                }
            }
        })
    }


    // #endregion
</script>

<style>
@import "@/assets/css/chessboard.css";
</style>